﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace AddBookCovers
{
    class AddCovers
    {
        private static void AddCover(DirectoryInfo dir)
        {
            BookstoreDataClassesDataContext context = new BookstoreDataClassesDataContext();
            using (context)
            {
                foreach (FileInfo file in dir.GetFiles())
                {
                    string isbn = file.Name.Split(new char[] { '.' }).First();
                    isbn = isbn.Trim();
                    var book =
                        from b in context.Books
                        where b.ISBN == isbn
                        select b;

                    if (book.Count() != 0)
                    {
                        AddCoverToDB(book.First(), file, context);
                    }
                }
            }
        }

        private static void AddCoverToDB(Book book, FileInfo file, BookstoreDataClassesDataContext context)
        {
            using (FileStream fs = new FileStream(file.FullName, FileMode.Open, FileAccess.Read))
            {
                byte[] fileBytes = new byte[fs.Length];
                int bytesRead = fs.Read(fileBytes, 0, (int)fs.Length);

                if (bytesRead > 0)
                {
                    Cover cover = new Cover
                    {
                        CoverFileName = file.Name,
                        CoverFile = fileBytes
                    };
                    context.Covers.InsertOnSubmit(cover);
                    context.SubmitChanges();
                    book.CoverId = cover.CoverId;
                    context.SubmitChanges();
                }
            }
        }

        static void Main()
        {
            DirectoryInfo dir = new DirectoryInfo("Images");
            AddCover(dir);
        }
    }
}
